import { globalProperties } from "./global-properties"

export function httpGet(path:string){
    return new Promise<any>((resolve, reject)=>{
        fetch(globalProperties().rootUrl+path,{
            method: 'GET',
            headers:{
                'content-type' : 'application/json;charset=UTF-8'
            },
            }).then(res => {
                if (!res.ok) {
                    return res.text().then(text => {
                        throw new Error(`【错误代码${res.status}】${text}`);
                    })
                }
                else {
                    return res.json()
                }
            }).then(data =>{
                if(data?.code == 0){
                    resolve(data.value)
                }else{
                    reject(data.message)
                }  
            }).catch(error => {
                reject(error.message)
            })
    })
}

export function httpPost(params: string, path: string){
    return new Promise<any>((resolve, reject)=>{
        fetch(globalProperties().rootUrl  + path,{
            method: 'POST',
            headers:{
                'content-type' : 'application/json;charset=UTF-8'
            },
            body:params,
            }).then(res => {
                if (!res.ok) {
                    return res.text().then(text => {
                        throw new Error(`【错误代码${res.status}】${text}`);
                    })
                }
                else {
                    return res.json()
                }
            }).then(data =>{
                if(data?.code == 0){
                    resolve(data.value)
                }else{
                    reject(data.message)
                }  
            }).catch(error => {
                reject(error.message)
            })
    })
}

export function httpPostExcel(params: string, path: string, fileName: string){
    return new Promise<any>((resolve, reject)=>{
        fetch(globalProperties().rootUrl  + path,{
            method: 'POST',
            headers:{
                'content-type' : 'application/json;charset=UTF-8'
            },
            body:params,
            }).then(async res => {
                if(!res.ok){ 
                    return res.text().then(text => {
                        throw new Error(`【错误代码${res.status}】${text}`);
                    })
                }else{
                    return res.blob()
                }
            }).then(blob =>{
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                let n = Date.now()
                a.download = fileName+n+'.xlsx';
                a.click();
                URL.revokeObjectURL(url);
                resolve('导出成功')
            }).catch(error => {
                reject(error.message)
            })
    })
}
